package com.zeyu.framework.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.zeyu.framework.core.common.mapper.JsonMapper;
import com.zeyu.framework.core.persistence.Page;
import com.zeyu.framework.core.persistence.entity.BaseEntity;
import com.zeyu.framework.core.web.BaseController;
import com.zeyu.framework.core.web.Result;
import com.zeyu.framework.modules.sys.entity.Dict;
import com.zeyu.framework.modules.sys.service.DictService;
import com.zeyu.framework.utils.StringUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 字典Controller
 */
@Controller
@RequestMapping(value = "/sys/dict")
public class DictController extends BaseController {

    // ================================================================
    // Constants
    // ================================================================

    // ================================================================
    // Fields
    // ================================================================

    @Autowired
    private DictService dictService;

    // ================================================================
    // Constructors
    // ================================================================

    // ================================================================
    // Methods from/for super Interfaces or SuperClass
    // ================================================================

    // ================================================================
    // Public or Protected Methods
    // ================================================================

    /**
     * 注解 @ModelAttribute 注释的方法会在此controller每个方法执行前被执行
     */
    @ModelAttribute
    public Dict get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return dictService.get(id);
        } else {
            return new Dict();
        }
    }

    /**
     * 字典列表页
     */
    @RequiresPermissions("sys:dict:view")
    @RequestMapping(value = {"", "index"})
    public String index(Model model) {
        List<String> typeList = dictService.findTypeList();
        model.addAttribute("typeList", typeList);
        return "modules/sys/dictList";
    }

    /**
     * 获取字典列表
     */
    @RequiresPermissions("sys:dict:view")
    @RequestMapping(value = "list")
    @ResponseBody
    public Page<Dict> list(HttpServletRequest request) {
        Page<Dict> page = new Page<>(request);
        // 查询扩展
        String extraSearch = page.getDatatablesCriterias().getExtraSearch();
        // 转换
        Dict dict = JsonMapper.getInstance().fromJson(extraSearch, Dict.class);
        if (dict == null) {
            dict = new Dict();
        }
        return dictService.findPage(page, dict);
    }

    /**
     * 更新字典
     */
    @RequiresPermissions("sys:dict:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(@Validated Dict dict) {
        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }
        if (StringUtils.isNoneBlank(dict.getId())) {
            // 更新操作,判断是否fixed
            if (dict.getFixed() == BaseEntity.FIX_FLAG_YES) {
                result.setStatus(Result.ERROR);
                result.setMessage("字典是锁定项目，不允许更新操作!");
                return result;
            }
        }
        dictService.save(dict);
        result.setStatus(Result.SUCCESS);
        result.setMessage("保存字典'" + dict.getLabel() + "'成功");

        return result;
    }

    /**
     * 删除字典
     */
    @RequiresPermissions("sys:dict:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public Result delete(Dict dict) {
        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }
        dictService.delete(dict);
        result.setStatus(Result.SUCCESS);
        result.setMessage("删除字典成功");
        return result;
    }

    /**
     * 删除多个字典
     */
    @RequiresPermissions("sys:dict:edit")
    @RequestMapping(value = "deleteList")
    @ResponseBody
    public Result deleteList(String[] idList) {
        Result result = new Result();
        if (MODE_DEMO) {
            result.setStatus(Result.ERROR);
            result.setMessage("演示模式，不允许操作!");
            return result;
        }

        if (idList != null && idList.length > 0) {
            dictService.deleteList(Arrays.asList(idList), new Dict());
        }

        result.setStatus(Result.SUCCESS);
        result.setMessage("删除字典成功");
        return result;
    }

    /**
     * 根据类型返回此类型的字典树
     *
     * @param type 字典类型
     * @return 字典树
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String type) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        Dict dict = new Dict();
        dict.setType(type);
        List<Dict> list = dictService.findList(dict);
        for (Dict e : list) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getParentId());
            map.put("name", StringUtils.replace(e.getLabel(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 根据类型返回此类型的字典列表
     *
     * @param type 字典类型
     * @return 字典列表
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "listData")
    public List<Dict> listData(@RequestParam(required = false) String type) {
        Dict dict = new Dict();
        dict.setType(type);
        return dictService.findList(dict);
    }

    // ================================================================
    // Getter & Setter
    // ================================================================

    // ================================================================
    // Private Methods
    // ================================================================

    // ================================================================
    // Inner or Anonymous Class
    // ================================================================

    // ================================================================
    // Test Methods
    // ================================================================
}
